/**
 * Created by jiexin on 2017/11/6.
 */
layui.use(['form', 'element', 'layer', 'table'], function() {
    var form = layui.form;
    var element = layui.element;
    var table = layui.table;
    var $ = layui.jquery;
    var layer = layui.layer;

    //
    form.on('submit(adduser)', function(data){
        console.log(data.field);
        var return_adddata = {"data": JSON.stringify(data.field), "type":1};
        userajaxopt(return_adddata);
        // $("#resetuser").trigger("click")
    });

    form.on('submit(moduser)', function(data){
        var moddata = data.field;
        // console.log(modifydata);
        // console.log(moddata);
        var return_moddata = {};
        $.each(modifydata, function (k,v) {
            if (moddata[k] !== v && moddata[k] !== undefined){
                return_moddata[k] = moddata[k];
                return_moddata["user_id"] = modifydata["uid"];
            }
        });
        if (moddata["password"] !== ""){
            return_moddata["password"] = moddata["password"];
            return_moddata["user_id"] = modifydata["uid"];
        }
        if (return_moddata["user_id"] !== undefined ){
            var return_all_data = {};
            return_all_data["data"] = JSON.stringify(return_moddata);
            return_all_data["type"] = 0;
            console.log(return_all_data);
            userajaxopt(return_all_data)
        } else {
            $("#resetuser").trigger("click");
            $("#password").attr('lay-verify', 'required');
            $('#adduser').css('display','inherit');
            $('#moduser').css('display', 'none');
        }
        // console.log(return_moddata);
    });

    function userajaxopt(udata) {
        $.ajax({
            url: "/user-opt-am/",
            dataType: 'json',
            type: 'POST',
            async:false,
            data: udata,
            success: function (statusdata) {
                console.log()
                if (statusdata["status"] === 0){
                    usertable.reload({
                         data: statusdata["data"]
                    });
                    if (udata["type"] === 0){
                        $("#resetuser").trigger("click");
                        $("#password").attr('lay-verify', 'required');
                        $('#adduser').css('display','inherit');
                        $('#moduser').css('display', 'none');
                    }else{
                        $("#resetuser").trigger("click")
                    }
                }else if (statusdata["status"] === 1){
                    layer.msg('操作失败！')
                }

            }
       })
    }



    //table user
    var u_a = document.getElementById('manage-left');
    var u_a_h = u_a.offsetHeight - 80;
    var u_a_w = u_a.offsetWidth;

    console.log(u_a_h, u_a_w);


    var table_format_user = [[
         {field: 'uid', align: 'center', title: 'ID', width: u_a_w * 0.1}
         , {field: 'name', align: 'center', title: '用户名', width: u_a_w * 0.2}
         , {field: 'username', align: 'center', title: '账户名', width: u_a_w * 0.2}
         // , {field: 'email', title: '邮箱', width: u_a_w}
         , {field: 'permissions_page', align: 'center', title: '权限', width: u_a_w * 0.15}
         , {field: 'is_using', title: '状态', width: u_a_w * 0.15,  templet: '#userstatus'}
         , {fixed: 'right',width: u_a_w * 0.2, align: 'center',  title: '操作', toolbar: '#userbutton'}
    ]];

    $('.layui-table-user').each(function() {
        //获取标签对于的一个属性
        var $obj = $(this);
        var tableid = $obj[0].id;
        var etaleid = '#' + tableid;
        var toolid = 'tool(' + tableid + ')';
        createtableu(etaleid,tableid,user_list,table_format_user, u_a_h);
        usertool(toolid,tableid);
    });


    var usertable;
    var pageint=1;
    function createtableu(etaleid,tableid,datas,table_format,table_height) {
        usertable = table.render({
            elem: etaleid,
            id: tableid,
            //url: '/demo/table/user/',
            // width: 440,
            height: table_height,
            limit: 10,
            page:true,
            data: datas,
            cols: table_format,
            done: function(res, curr, count){
                pageint = curr
            }
        });
    }

    var modifydata;
    function usertool(toolid, tableid) {
        //监听工具条
        //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        table.on(toolid, function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            var checkStatus = table.checkStatus(tableid);
            //tr.index()
            if (layEvent === 'modifyuser') {

                if (data["is_using"] === 1){
                    $('#moduser').css('display','inherit');
                    $('#adduser').css('display', 'none');
                    $("#password").removeAttr('lay-verify');
                    var tindex = (pageint - 1) * 10 + tr.index();
                    modifydata = user_list[tr.index()];
                    $("#username").val(modifydata["username"]);
                    $("#name").val(modifydata["name"]);
                    $("#email").val(modifydata["email"]);
                    $("#permissions_page").val(modifydata["permissions_page"]);
                }else{
                    layer.msg("禁用状态，不允许修改！")
                }
            }else if (layEvent === 'disuser') {
                if (data["permissions_page"] === 'all'){
                    layer.msg('无权限禁用')
                }else{
                    dissend(tr,0)
                }
            }else if (layEvent === 'enuser') {
                if (data["permissions_page"] === 'all'){
                    layer.msg('无权限禁用')
                }else {
                    dissend(tr, 1)
                }
            }else if (layEvent === 'deluser') {
                if (data["permissions_page"] === 'all'){
                    layer.msg('无权限删除')
                }else {
                    $.ajax({
                        url: "/user-opt/",
                        dataType: 'json',
                        type: 'POST',
                        data: {"id": data["uid"], "type": 2},
                        success: function (statusdata) {
                            usertable.reload({
                                data: statusdata["data"]
                            });
                        }
                    })
                }
            }
        });
    }

    function dissend(sendtr,sendstatus) {
        $.ajax({
            url: '/user-opt/',
            dataType: 'json',
            type: 'POST',
            data: {"id": user_list[sendtr.index()]["uid"], "status":sendstatus, "type": 0},
            success: function (statusdata) {
                if (statusdata["status"] === 0) {
                    if (sendstatus === 1){
                        sendtr.find("td").find(".laytable-cell-1-is_using").html('<span class="label label-success">已启用</span>');
                        sendtr.find("td").find(".laytable-cell-1-5").find(".handle-btn-start").replaceWith('<span title="停用" class="handle-btn handle-btn-stop"  lay-event="disuser"><i class="layui-icon">&#xe651;</i></span>');
                        user_list[sendtr.index()]["is_using"] = sendstatus;
                        layer.msg("启用成功！")
                    } else {
                        sendtr.find("td").find(".laytable-cell-1-is_using").html('<span class="label label-default">已禁用</span>');
                        sendtr.find("td").find(".laytable-cell-1-5").find(".handle-btn-stop").replaceWith('<span title="启用" class="handle-btn  handle-btn-start" lay-event="enuser"><i class="layui-icon">&#xe652;</i></span>');
                        user_list[sendtr.index()]["is_using"] = sendstatus;
                        layer.msg("禁用成功！")
                    }
                } else {
                    layer.msg("状态修改失败")
                }
            }
        })
    }



    //
    form.on('submit(addrule)', function(data){
        console.log(data.field);
        var r_opt_data = data.field;
        r_opt_data["type"] = 1;
        ruleajaxopt(r_opt_data);
        $("#emptyrule").trigger("click");
    });

    // rule table
    var r_a = document.getElementById('manage-right');
    var r_a_h = r_a.offsetHeight - 350;
    var r_a_w = r_a.offsetWidth;

    console.log(r_a_h, r_a_w);

    var table_format_rule = [[
        {checkbox:true, align: 'center'}
         , {field: 'permissions', align: 'center', title: '标识', width: r_a_w * 0.17}
         , {field: 'describe', align: 'center', title: '权限描述', width: r_a_w * 0.5}
         , {fixed: 'right',width: r_a_w * 0.17, align: 'center',  title: '操作', toolbar: '#ruleDemo'}
    ]];
    $('.layui-table-rule').each(function() {
        //获取标签对于的一个属性
        var $obj = $(this);
        var tableid = $obj[0].id;
        var etaleid = '#' + tableid;
        var toolid = 'tool(' + tableid + ')';
        createtabler(etaleid,tableid,rule_list,table_format_rule, r_a_h);
        ruletool(toolid,tableid);
    });


    var ruletable;

    function createtabler(etaleid,tableid,datas,table_format,table_height) {
        ruletable = table.render({
            elem: etaleid,
            id: tableid,
            height: table_height,
            data: datas,
            cols: table_format
        });
        active = {
            getCheckLength: function () {
                var get_list_data = [];
                var get_txt_data = "";
                var checkStatus = table.checkStatus(tableid);
                var data = checkStatus.data;
                layer.msg('添加了：' + data.length + ' 个');
                for (var i=0; i<data.length; i++) {
                    if ($.inArray(data[i]["permissions"], get_list_data) === -1) {
                        get_list_data.push(data[i]["permissions"]);
                        if ( get_txt_data === ""){
                            get_txt_data = get_txt_data + data[i]["permissions"];
                        }else{
                            get_txt_data = get_txt_data + ',' + data[i]["permissions"];
                        }

                    }
                }
                console.log(get_txt_data);
                $("#permissions_page").val(get_txt_data)
            }
        }
    }

    function ruletool(toolid, tableid) {
        //监听工具条
        //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        table.on(toolid, function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            var checkStatus = table.checkStatus(tableid);

            //tr.index()
            if (layEvent === 'delrule') {
                var r_opt_data = {"data":data["permissions"], "type":0};
                ruleajaxopt(r_opt_data)
            }
        });
    }

    function ruleajaxopt(rdata) {
        $.ajax({
            url: "/rule-opt/",
            dataType: 'json',
            type: 'POST',
            data: rdata,
            success: function (statusdata) {
                if (statusdata["status"] === 0){
                    ruletable.reload({
                         data: statusdata["data"]
                    });
                }else if (statusdata["status"] === 1){
                    layer.msg('操作失败！')
                }else{
                    layer.msg('ID重复，添加失败！')
                }

            }
       })
    }

    $('.demoTable .layui-btn').on('click', function() {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

});